import sys
import os
import copy
import logging

sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))

from command_parser.strip_parse.strip_command_parser import StripParser
from utils.common_utils import *
from configure.compiler_configure import *
from base.context import Context
from utils.db_object_pool import DBObjectPool
from configure.config_logging import capture_log_init


class StripHandler(object):
    
    def __init__(self, command=[]):
        self.command = command
        self.env = {}
        self.cwd = ""
        self.context = Context()
        self.capture_db_handler = None
        self.cache_db_handler = None

    def init_env(self):
        self.env = dict(os.environ)
        self.cwd = os.getcwd()
        remove_envs_by_keys(env=self.env, remove_list=["LD_PRELOAD"])
        self.context.update_work_path(os.path.dirname(self.env["IRGEN_WORK_PATH"]))
        self.init_logger()
        self.context.check_redis_cached_config()
        self.capture_db_handler = DBObjectPool.get_db_inst_by_name("strip")
    
    def init_logger(self):
        capture_log_init(log_dir=self.context.LOG_DIR, log_mode="a", log_name="strip.log", log_level="DEBUG")
    
    def run_strip_handler(self):
        
        parser = StripParser(command=self.command, context=self.context)
        strip, options = parser.parse_command()
        strip = real_binary_path(strip)
        ret = run_command(command=self.command)
        logging.debug("Record command: {}".format(" ".join(self.command)))
        # print("[INFO] Capture Strip Command: %s" % ' '.join(self.command))
        self.record_command(parser=parser)
        return ret
    
    def record_command(self, parser=None):
        
        input_opts = parser.get_input_options()
        input_files = [os.path.abspath(opt.parameter[0]) for opt in input_opts]
        input_files_md5 = [file_md5(file) for file in input_files]
        
        command = parser.get_original_command()
        ret = run_command(command=command, env=self.env)
        
        output_opts = parser.get_output_options()
        output_files = [os.path.abspath(opt.parameter[0]) for opt in output_opts]
        output_files_md5 = [file_md5(file) for file in output_files]
        self.save_dep_info(output_files=output_files, outputs_md5=output_files_md5, input_files=input_files,inputs_md5=input_files, command=command )
        return ret
        
    def save_dep_info(self, output_files=[], outputs_md5=[], input_files=[], inputs_md5=[], command=[]):
        for output_file, output_md5, input_file, input_md5 in zip(output_files, outputs_md5, input_files, inputs_md5):
            self.capture_db_handler.set_name_dep(output_md5, output_file)
            self.capture_db_handler.set_name_dep(input_md5, input_file)
            self.capture_db_handler.set_link_dep(output_md5, input_md5)
        
        self.capture_db_handler.set_cmd_dep(output_md5, [self.cwd, command])
        

if __name__ == "__main__":
    build_command = sys.argv[2:]
    handler = StripHandler(command=build_command)
    handler.init_env()
    handler.run_strip_handler()